package com.xinqi.modules.chat.chat.official.controller.notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xinqi.common.core.constant.ChatRemindConstants;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentUpdateDTO;
import com.xinqi.modules.chat.chat.official.service.ChatAssistantContentService;
import io.rong.models.response.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * APP -- 新奇助手通知设置
 *
 * @author: yyzhen
 * @date: 2023/05/05
 */
@RestController
@RequestMapping("/assistant")
@RequiredArgsConstructor
@Log4j2
public class ChatAssistantContentNotifyController {

    private final ChatAssistantContentService chatAssistantContentService;

    /**
     * 新奇助手获取消息内容
     */
    @Operation(summary = "新奇助手获取校验")
    @PostMapping("/notify")
    public ResponseResult notify(String signature) {
        ResponseResult response = new ResponseResult(200,"成功");
        return response;
    }

    /**
     * 新奇助手获取消息内容
     */
    @Operation(summary = "新奇助手获取返回消息内容")
    @PostMapping("/message")
    public ResponseResult message(HttpServletRequest request) {

        // 解析融云消息内容主要信息
        String objectName = request.getParameter( "objectName");
        String content = request.getParameter( "content");
        String messageId = request.getParameter("msgUID");
        String msgTimestamp = request.getParameter("msgTimestamp");

        // 回调，反哺融云消息ID、发送时间
        try {
            boolean flag = false;
            if (Objects.equals(ChatRemindConstants.REMIND_OBJECT_NAME, objectName)) {

            } else {
                String message = JSON.parseObject(content).getString("content");
                JSONObject json = JSON.parseObject(message);
                ChatAssistantContentUpdateDTO update = new ChatAssistantContentUpdateDTO();
                update.setId(json.getLongValue("id"));
                update.setMsgUid(messageId);
                update.setMessageTime(Long.parseLong(msgTimestamp));
                flag = chatAssistantContentService.update(update);
            }
            if (flag) {
                log.info("解析消息成功");
            } else {
                log.info("解析消息失败");
            }
        } catch (Exception e) {
            log.info("=======融云消息回调异常=======",e);
        }
        return new ResponseResult(200,"获取成功");
    }

}
